package com.game.api.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.game.api.annotation.Token;
import com.game.core.domain.PrStaff;
import com.game.core.resp.ResponeData;
import lombok.extern.slf4j.Slf4j;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ApiAuthInterceptor implements HandlerInterceptor {

    /**
     * 过期时间
     */
    public static int time = 24*60*60;
    /**
     * 用户登录缓存
     */
    public static ExpiringMap<String, PrStaff> tokenMap = ExpiringMap.builder()
            .expiration(time, TimeUnit.SECONDS)
            .expirationPolicy(ExpirationPolicy.ACCESSED)
            .variableExpiration()
            .build();
    /**
     * 登陆超时
     *
     * @param response
     * @return
     * @throws Exception
     */
    public static boolean offLogin(HttpServletResponse response) throws Exception {
        ResponeData responeData = ResponeData.builder().build().tokenInvalld();
        String jsonString = JSON.toJSONString(responeData, SerializerFeature.WriteDateUseDateFormat);
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(403);
        response.getWriter().write(jsonString);
        response.getWriter().flush();
        response.getWriter().close();
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception err)
            throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav)
            throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof ResourceHttpRequestHandler) {
            return true;
        }

        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            log.debug("method:{}", method.getMethod().getName());
            Token tokenAnno = method.getMethodAnnotation(Token.class);
            if (tokenAnno != null) {
                if (!tokenAnno.has()) {
                    return true;
                }
            }
        }


        String token = request.getHeader("Access-Token");
        log.debug("token:{}", token);
        if (StringUtils.isBlank(token)) {
            return offLogin(response);
        }

        PrStaff prStaff = tokenMap.get(token);
        if (prStaff == null) {
            return offLogin(response);
        } else {
            tokenMap.put("token", prStaff, ExpirationPolicy.ACCESSED, time, TimeUnit.MINUTES);
            return true;
        }
    }

}